import { prisma } from "@/lib/prisma"
import { getServerSession } from "next-auth"
import { NextResponse } from "next/server"
import { authOptions } from "@/lib/auth"

export async function POST(req: Request) {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) {
      return NextResponse.json({ error: "未授权访问" }, { status: 401 })
    }

    const { libraries } = await req.json()

    // 从选中的事件库中获取所有事件
    const events = await prisma.event.findMany({
      where: {
        libraryId: {
          in: libraries
        }
      },
      select: {
        id: true,
        title: true,
        date: true,
        description: true
      }
    })

    if (events.length < 5) {
      return NextResponse.json(
        { error: "所选事件库中的事件数量不足" },
        { status: 400 }
      )
    }

    // 生成10轮游戏
    const rounds = Array.from({ length: 10 }, () => {
      // 为每轮随机生成一个目标日期（1000年到2000年之间）
      const targetDate = new Date(
        Math.floor(Math.random() * (2000 - 1000 + 1) + 1000),
        Math.floor(Math.random() * 12),
        Math.floor(Math.random() * 28) + 1
      ).toISOString()

      // 随机选择5个事件
      const roundEvents = [...events]
        .sort(() => Math.random() - 0.5)
        .slice(0, 5)

      return {
        targetDate,
        events: roundEvents,
        selectedEventId: null,
        score: 0
      }
    })

    // 创建新游戏记录
    const game = await prisma.game.create({
      data: {
        userId: session.user.id,
        score: 0,
        rounds: rounds as any
      }
    })

    return NextResponse.json({
      gameId: game.id,
      rounds
    })

  } catch (error) {
    console.error("Game start error:", error)
    return NextResponse.json(
      { error: "创建游戏失败" },
      { status: 500 }
    )
  }
} 